package com.holly.unit.deform;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.holly.unit.db.api.factory.PageFactory;
import com.holly.unit.db.api.factory.PageResultFactory;
import com.holly.unit.db.api.pojo.page.PageResult;
import com.holly.unit.deform.api.DeformTempletApi;
import com.holly.unit.deform.api.exception.DeformException;
import com.holly.unit.deform.api.exception.enums.DeformExceptionEnum;
import com.holly.unit.deform.api.pojo.templet.DesignFormTempletDTO;
import com.holly.unit.deform.api.pojo.templet.DesignFormTempletRequest;
import com.holly.unit.deform.context.DeformContext;
import com.holly.unit.deform.entity.DesignFormTemplet;
import com.holly.unit.deform.service.DeformTempletService;
import com.holly.unit.office.api.OfficeExcelApi;
import com.holly.unit.office.api.pojo.report.ExcelExportParam;
import com.holly.unit.query.api.QueryApi;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;

/**
 * 类描述: 表单设计器模板操作类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/7 11:39
 */
public class DeformTempletOperator implements DeformTempletApi<DesignFormTemplet>{

    private DeformTempletService templetService = DeformContext.deformTempletService();

    private OfficeExcelApi officeExcelApi = DeformContext.officeExcelApi();

    private QueryApi queryApi = DeformContext.queryApi();


    @Override
    public void add(DesignFormTempletRequest designFormTempletRequest) {
        DesignFormTemplet designFormTemplet = new DesignFormTemplet();
        BeanUtil.copyProperties(designFormTempletRequest, designFormTemplet);
        templetService.save(designFormTemplet);
    }

    @Override
    public void del(DesignFormTempletRequest designFormTempletRequest) {
        templetService.removeById(designFormTempletRequest.getId());
    }

    @Override
    public void edit(DesignFormTempletRequest designFormTempletRequest) {

        DesignFormTemplet designFormTemplet = new DesignFormTemplet();
        BeanUtil.copyProperties(designFormTempletRequest, designFormTemplet);
        templetService.updateById(designFormTemplet);

    }

    @Override
    public DesignFormTempletDTO detail(DesignFormTempletRequest designFormTempletRequest) {
        DesignFormTempletDTO dto = new DesignFormTempletDTO();
        DesignFormTemplet designFormTemplet = templetService.getById(designFormTempletRequest.getId());
        BeanUtil.copyProperties(designFormTemplet,dto);
        return dto;
    }

    @Override
    public List<DesignFormTempletDTO> findList(DesignFormTempletRequest designFormTempletRequest) {
        List<DesignFormTemplet> list = templetService.list(this.createWrapper(designFormTempletRequest));
        List<DesignFormTempletDTO> dtos = new ArrayList<>();
        list.stream().forEach(entity->{
            DesignFormTempletDTO dto = new DesignFormTempletDTO();
            BeanUtil.copyProperties(entity,dto);
            dtos.add(dto);
        });
        return dtos;
    }

    @Override
    public PageResult<DesignFormTempletDTO> findPage(DesignFormTempletRequest designFormTempletRequest) {
        Page<DesignFormTemplet> page = templetService.page(PageFactory.defaultPage(), this.createWrapper(designFormTempletRequest));
        PageResult<DesignFormTemplet> pageResult = PageResultFactory.createPageResult(page);
        List<DesignFormTempletDTO> dtos = new ArrayList<>();
        pageResult.getRows().stream().forEach(entity->{
            DesignFormTempletDTO dto = new DesignFormTempletDTO();
            BeanUtil.copyProperties(entity,dto);
            dtos.add(dto);
        });
        return createDtoPageResult(pageResult, dtos);
    }

    @Override
    public void export(HttpServletResponse response) {

        ExcelExportParam excelExportParam = new ExcelExportParam();
        List<DesignFormTemplet> designFormTempletList = templetService.list();

        excelExportParam.setClazz(DesignFormTemplet.class);
        excelExportParam.setDataList(designFormTempletList);
        excelExportParam.setExcelTypeEnum(ExcelTypeEnum.XLS);
        excelExportParam.setFileName("系统用户导出");
        excelExportParam.setResponse(response);

        officeExcelApi.easyExportDownload(excelExportParam);
    }

    @Override
    public List<Map<String, Object>> findAnalysisOptions(String label,String value,Boolean useId,Boolean returnJson) {

        // 查询所有
        List<DesignFormTemplet> list = templetService.list();
        // 封装
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (DesignFormTemplet item : list) {
            Map<String, Object> map = new HashMap<String, Object>(3);
            map.put(label, item.getTempletName());
            if (useId == true) {
                map.put(value, item.getId());
            } else {
                map.put(value, item.getTempletCode());
            }
            if (returnJson == true) {
                map.put("templetJson", item.getTempletJson());
            }
            result.add(map);
        }
        return result;
    }

    @Override
    public PageResult<DesignFormTemplet> page(DesignFormTemplet designFormTemplet, Map<String,String[]> paramMap) {
        QueryWrapper<DesignFormTemplet> queryWrapper = queryApi.initQueryWrapper(designFormTemplet, paramMap);
        Page<DesignFormTemplet> page = templetService.page(PageFactory.defaultPage(), queryWrapper);
        PageResult<DesignFormTemplet> pageResult = PageResultFactory.createPageResult(page);
        return pageResult;
    }

    @Override
    public void delBatch(List<String> ids) {
        if (ObjectUtil.isNull(ids) || ids.size() == 0) {
            throw new DeformException(DeformExceptionEnum.DEFORM_DEL_PARAM_ERROR);
        }
        templetService.removeByIds(ids);
    }

    @Override
    public void delBatch(String ids) {
        if (ids == null || "".equals(ids.trim())) {
            throw new DeformException(DeformExceptionEnum.DEFORM_DEL_PARAM_ERROR);
        } else {
            delBatch(Arrays.asList(ids.split(",")));
        }
    }

    @Override
    public DesignFormTemplet fetchEntity(LambdaQueryWrapper<DesignFormTemplet> queryWrapper) {
        DesignFormTemplet one = templetService.getOne(queryWrapper);
        if (ObjectUtil.isNull(one)) {
            throw new DeformException(DeformExceptionEnum.DEFORM_QUERY_BY_ID_ERROR,one);
        }
        return one;
    }

    @Override
    public DesignFormTemplet fetchEntityById(Serializable id) {
        DesignFormTemplet one = templetService.getById(id);
        if (ObjectUtil.isNull(one)) {
            throw new DeformException(DeformExceptionEnum.DEFORM_QUERY_BY_ID_ERROR,one);
        }
        return one;
    }

    @Override
    public DesignFormTemplet fetchEntityByCode(String code) {
        LambdaQueryWrapper<DesignFormTemplet> warpper = new LambdaQueryWrapper<DesignFormTemplet>();
        warpper.eq(DesignFormTemplet::getTempletCode, code);
        return fetchEntity(warpper);
    }

    private PageResult<DesignFormTempletDTO> createDtoPageResult(PageResult<DesignFormTemplet> pageResult, List<DesignFormTempletDTO> dtos) {
        PageResult<DesignFormTempletDTO> res = new PageResult<>();
        res.setRows(dtos);
        res.setTotalRows(Convert.toInt(pageResult.getTotalRows()));
        res.setPageNo(pageResult.getPageNo());
        res.setPageSize(pageResult.getPageSize());
        res.setTotalPage(PageUtil.totalPage(pageResult.getTotalRows(), pageResult.getPageSize()));
        return res;
    }

    /**
     * 构建wrapper
     *
     * @author holly
     * @date 2021/1/13 10:50
     */
    private LambdaQueryWrapper<DesignFormTemplet> createWrapper(DesignFormTempletRequest designFormTempletRequest) {
        LambdaQueryWrapper<DesignFormTemplet> queryWrapper = new LambdaQueryWrapper<>();

        // SQL拼接
        //queryWrapper.eq(ObjectUtil.isNotNull(dictRequest.getDictId()), SysDict::getDictId, dictRequest.getDictId());
        queryWrapper.eq(ObjectUtil.isNotNull(designFormTempletRequest.getUpdateUser()), DesignFormTemplet::getUpdateUser, designFormTempletRequest.getUpdateUser());
        queryWrapper.eq(ObjectUtil.isNotNull(designFormTempletRequest.getCreateUser()), DesignFormTemplet::getCreateUser, designFormTempletRequest.getCreateUser());
        queryWrapper.eq(ObjectUtil.isNotNull(designFormTempletRequest.getTempletJson()), DesignFormTemplet::getTempletJson, designFormTempletRequest.getTempletJson());
        queryWrapper.eq(ObjectUtil.isNotNull(designFormTempletRequest.getTempletName()), DesignFormTemplet::getTempletName, designFormTempletRequest.getTempletName());
        queryWrapper.eq(ObjectUtil.isNotNull(designFormTempletRequest.getTempletCode()), DesignFormTemplet::getTempletCode, designFormTempletRequest.getTempletCode());
        queryWrapper.eq(ObjectUtil.isNotNull(designFormTempletRequest.getId()), DesignFormTemplet::getId, designFormTempletRequest.getId());
        return queryWrapper;
    }
}
